'use strict';

/**
 * @ngdoc function
 * @name webApp.controller:SearchCtrl
 * @description
 * # SearchCtrl
 * Controller of the webApp
 */

angular.module('webApp')
  .controller('search', function ($scope,promiseSearch,cookie,$timeout,$filter,$ionicScrollDelegate) {
    var filter = _.memoize(function(data){
      return $filter('trustHtml',data)
    })();
    //初始页码
    var page = 1;
    $scope.scroll = false;
      $scope.infinite = false;
    $scope.search = {
      data: ''
    };
    $scope.infinite = false;
    //搜索操作
    $scope.clear = function(){
      page = 1;
      $scope.search.data = '';
      $scope.searchBars = [];
      $scope.searchBars = false;
    };
    //搜索内容
    $scope.search = function(){
      $scope.searchBars = [];
      $scope.searchBars = false;
      $scope.infinite = false;
      page = 1;
      promiseSearch.search($scope.search.data,1,20).then(function(data){
        if(data.length != 0){
          page = 2;
          angular.forEach(data,function(obj){
            obj.title = filter(obj.title);
            obj.origin = filter(obj.origin);
          });
          $scope.searchBars = data;
          $scope.shearchId = function(id){
            cookie.setCookie('newsId',id);
          };
          $timeout(function(){
            $ionicScrollDelegate.resize();
            $scope.infinite = true;
          });
        }
        else{
          $scope.infinite = false;
        }
      });
    };
    $scope.loadMore = function(){
      $scope.infinite = false;
      promiseSearch.search($scope.search.data,page,20).then(function(data){
        page += 1;
        if(data.length != 0){
          angular.forEach(data,function(obj){
            obj.title = filter(obj.title);
            obj.origin = filter(obj.origin);
          });
          $scope.searchBars = _.union($scope.searchBars,data);
          $scope.shearchId = function(id){
            cookie.setCookie('newsId',id);
          };
          $timeout(function(){
            $ionicScrollDelegate.resize();
            $scope.infinite = true;
          },1000);
        }
        else{
          $scope.infinite = false;
        }
      });
    };
});
